package com.gis.premd;

import com.gis.beans;
import com.gis.util.UtilsClass;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * @author leon
 * @ClassName PreReducer.java
 * @createTime 2021年09月26日 12:13:00
 */
public class PreReducer extends Reducer<Text, beans, beans, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<beans> values, Context context) throws IOException, InterruptedException {

        ArrayList<beans> initList = new ArrayList<>();
        ArrayList<beans> filterList = new ArrayList<>();
        for (beans value : values) {
            initList.add(UtilsClass.getNewbeans(value));
        }

        // 排序
        initList.sort(new Comparator<beans>() {
            @Override
            public int compare(beans o1, beans o2) {
                return o1.compareTo(o2);
            }
        });

        for (int i = 0; i < initList.size() - 1; i++) {
            int j = i + 1;
            if (UtilsClass.getStance(initList.get(i), initList.get(j)) > 1000){
                filterList.add(UtilsClass.getNewbeans(initList.get(j)));
            }
            else if (UtilsClass.getStance(initList.get(i), initList.get(j)) > 400){
                // 插值
                ArrayList<beans> newBeans = UtilsClass.insertPoint(initList.get(i), initList.get(j));
                for (beans newBean : newBeans) {
                    initList.add(UtilsClass.getNewbeans(newBean));
                }
            }
            while (UtilsClass.getStance(initList.get(i), initList.get(j)) < 200){
                j = j + 1;
            }
            filterList.add(UtilsClass.getNewbeans(initList.get(j)));
            i = j - 1;
        }

        // 写出
        for (beans beans : filterList) {
            context.write(beans, NullWritable.get());
        }

    }
}
